package com.itheima.d2_xml;


import org.dom4j.Document;
import org.dom4j.DocumentException;
import org.dom4j.Element;
import org.dom4j.io.SAXReader;

import java.io.File;
import java.util.ArrayList;
import java.util.List;

public class Demo4jDemo1 {
    public static void main(String[] args) throws DocumentException {
        String path = "D:\\APP\\IT\\code\\javase-pro\\properties-xml-logback-app\\xml_test\\book.xml";
        try {
            List<Contact> contactList = parseXml(path);
            //遍历集合
            contactList.forEach(contact -> System.out.println(contact));
        } catch (Exception e) {
            throw new RuntimeException(e);

        }
    }



        public static List<Contact> parseXml(String path) throws DocumentException {
            //基于给定的路径进行有效校验
            File file = new File(path);
            if (!file.exists()) {
                throw new RuntimeException("给定的文件路径不存在");
            }
            if (!file.isFile()) {
                throw new RuntimeException("非法文件");

            }


            //创建集合
            List<Contact> contactList = new ArrayList<>();
            //1\加载读取xml文件，生成Dociment对昂
            Document document = new SAXReader().read(file);
            //2 使用Document对象，获取根元素
            Element rootElement = document.getRootElement();
            //3 利用根元素一层层解析xml内容
            List<Element> contactEls = rootElement.elements();
            for (Element contact : contactEls) {
                /*解析XML中的联系人相关数据*/
                //获取id属性值
                String id = contact.attributeValue("id");
                //获取vip属性值
                String vip = contact.attributeValue("vip");

                //获取name元素值
                String name = contact.elementText("name");//根据子元素名字，获取子元素中的文本内容
                //获取gender元素值
                String gender = contact.elementText("gender");
                //获取email元素值
                String email = contact.elementText("email");

                /*把联系人相关数据封装到实例对象中*/
                Contact c = new Contact();
                c.setId(Integer.parseInt(id));
                c.setVip(Boolean.parseBoolean(vip));
                c.setName(name);
                c.setEmail(email);
                c.setGender(gender);

                /*把联系人对象存储到集合中*/
                contactList.add(c);
            }

            return contactList;
        }

}

